import os
import shutil
import sys
from PyQt5.QtWidgets import QApplication, QMainWindow, QPushButton, QLabel, QComboBox, QVBoxLayout, QHBoxLayout, \
    QWidget, QMessageBox, QColorDialog, QInputDialog, QSizePolicy, QSpacerItem, QDialog, QListWidget, QFileDialog
from PyQt5.QtGui import QColor, QIcon, QPixmap, QPalette, QBrush, QPainter, QPen
from PyQt5.QtCore import Qt, QTimer
import cv2
import numpy as np
import time
import keyboard
import ctypes
from ctypes import wintypes
from pynput import mouse
import configparser
import zhunxing

# 准星参数
crosshair_color = (203, 192, 255)
crosshair_size = 5
crosshair_thickness = 1
is_visible = True
mode = "Short Press"
crosshair_style = "Cross"
mod_crosshair_path = ''  # 初始化模版准星路径

# 配置文件路径
config_file = 'Config.ini'

# 读取配置文件
def read_config():
    global crosshair_color, crosshair_size, crosshair_thickness, mode, crosshair_style, mod_crosshair_path
    config = configparser.ConfigParser()
    if config.read(config_file):
        crosshair_color = tuple(map(int, config['Crosshair']['Color'].split(',')))
        crosshair_size = config['Crosshair'].getint('Size')
        crosshair_thickness = config['Crosshair'].getint('Thickness')
        mode = config['Crosshair']['Mode']
        crosshair_style = config['Crosshair']['Style']
        mod_crosshair_path = config['Crosshair'].get('ModCrosshairPath', '')

# 写入配置文件
def write_config():
    config = configparser.ConfigParser()
    config['Crosshair'] = {
        'Color': ','.join(map(str, crosshair_color)),
        'Size': str(crosshair_size),
        'Thickness': str(crosshair_thickness),
        'Mode': mode,
        'Style': crosshair_style,
        'ModCrosshairPath': mod_crosshair_path
    }
    with open(config_file, 'w') as configfile:
        config.write(configfile)

# 检查配置文件是否存在，不存在则创建并写入默认值
if not configparser.ConfigParser().read(config_file):
    write_config()
else:
    read_config()

# 监听鼠标事件
def on_click(x, y, button, pressed):
    global is_visible, mode

    if button == mouse.Button.right:
        if mode == "Short Press":
            if not pressed:
                is_visible = not is_visible
        elif mode == "Long Press":
            is_visible = not pressed

def update_crosshair_settings():
    global crosshair_color, crosshair_size, crosshair_thickness, mod_crosshair_path

    # 选择颜色
    color_dialog = QColorDialog(QColor(*crosshair_color[::-1]), None)
    color_dialog.setOption(QColorDialog.NoButtons, False)  # 不禁用按钮
    color_dialog.setOption(QColorDialog.ShowAlphaChannel, False)  # 不显示透明度通道
    color_dialog.setWindowTitle("选择准星颜色")
    if color_dialog.exec_() == QColorDialog.Accepted:
        color_code = color_dialog.selectedColor()
        crosshair_color = (color_code.blue(), color_code.green(), color_code.red())  # 转换为 BGR 格式

    # 输入大小
    size_input, ok = QInputDialog.getInt(None, "输入", "输入准星大小:", crosshair_size, 1, flags=Qt.WindowCloseButtonHint)
    if ok:
        crosshair_size = size_input

    # 输入粗细
    thickness_input, ok = QInputDialog.getInt(None, "输入", "输入准星粗细:", crosshair_thickness, 1, flags=Qt.WindowCloseButtonHint)
    if ok:
        crosshair_thickness = thickness_input

    # 更新配置文件
    write_config()
    redraw_crosshair(window)

def update_mode(index):
    global mode
    mode = mode_combobox.itemText(index)
    write_config()

def update_style(index):
    global crosshair_style
    crosshair_style = style_combobox.itemText(index)
    write_config()
    redraw_crosshair(window)

def redraw_crosshair(window):
    screen_width = ctypes.windll.user32.GetSystemMetrics(0)
    screen_height = ctypes.windll.user32.GetSystemMetrics(1)
    hdc = zhunxing.get_screen_dc()
    image = np.zeros((screen_height, screen_width, 4), dtype=np.uint8)  # 4 channels for RGBA

    if window.current_mod_image is not None:
        zhunxing.draw_custom_crosshair(hdc, screen_width, screen_height, window.current_mod_image, True, image)
    else:
        zhunxing.draw_crosshair_by_style(hdc, screen_width, screen_height, crosshair_color, crosshair_size, crosshair_thickness, True, crosshair_style, image)

    zhunxing.release_screen_dc(hdc)
    cv2.imwrite('crosshair.png', image)
    print("Crosshair image saved as crosshair.png")
    if window is not None:
        window.overlay.update_crosshair_image()

class Overlay(QWidget):
    def __init__(self):
        super().__init__()
        self.setWindowFlags(Qt.WindowStaysOnTopHint | Qt.FramelessWindowHint | Qt.WindowTransparentForInput | Qt.Tool)
        self.setAttribute(Qt.WA_TranslucentBackground)
        self.setGeometry(0, 0, ctypes.windll.user32.GetSystemMetrics(0), ctypes.windll.user32.GetSystemMetrics(1))
        self.crosshair_pixmap = QPixmap('crosshair.png')
        if self.crosshair_pixmap.isNull():
            print("Failed to load crosshair.png")

    def paintEvent(self, event):
        painter = QPainter(self)
        if is_visible:
            painter.drawPixmap(0, 0, self.crosshair_pixmap)

    def update_crosshair_image(self):
        self.crosshair_pixmap = QPixmap('crosshair.png')
        if self.crosshair_pixmap.isNull():
            print("Failed to load crosshair.png")
        self.update()

class MainWindow(QMainWindow):
    def __init__(self):
        super().__init__()

        self.setWindowTitle("准星辅助")
        self.setFixedSize(300, 300)
        self.setWindowIcon(QIcon('data/sk.ico'))
        self.screen_width, self.screen_height = ctypes.windll.user32.GetSystemMetrics(0), ctypes.windll.user32.GetSystemMetrics(1)

        # 添加 current_mod_image 属性
        self.current_mod_image = None
        self.load_mod_crosshair()

        main_layout = QVBoxLayout()

        background_pixmap = QPixmap('data/b.png').scaled(300, 300, Qt.IgnoreAspectRatio, Qt.SmoothTransformation)
        background_brush = QBrush(background_pixmap)
        palette = QPalette()
        palette.setBrush(QPalette.Window, background_brush)
        self.setPalette(palette)

        update_button = QPushButton("更新设置")
        update_button.setStyleSheet("""
            QPushButton {
                background-color: rgba(255, 192, 203, 128);
                border-radius: 15px;
                width: 135px;
                height: 40px;
            }
            QPushButton:hover {
                background-color: rgba(255, 182, 193, 128);
            }
        """)
        update_button.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)
        update_button.clicked.connect(update_crosshair_settings)

        mod_crosshair_button = QPushButton("选择模版准星")
        mod_crosshair_button.setStyleSheet("""
            QPushButton {
                background-color: rgba(255, 192, 203, 128);
                border-radius: 15px;
                width: 135px;
                height: 40px;
            }
            QPushButton:hover {
                background-color: rgba(255, 182, 193, 128);
            }
        """)
        mod_crosshair_button.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)
        mod_crosshair_button.clicked.connect(self.select_mod_crosshair)

        global mode_combobox
        mode_combobox = QComboBox()
        mode_combobox.addItems(["Short Press", "Long Press"])
        mode_combobox.setCurrentText(mode)
        mode_combobox.setStyleSheet("""
            QComboBox {
                background-color: rgba(255, 192, 203, 128);
                border-radius: 15px;
                padding: 5px;
                width: 100px;
                height: 30px;
            }
            QComboBox::drop-down {
                subcontrol-origin: padding;
                subcontrol-position: top right;
                width: 20px;
                border-left-width: 1px;
                border-left-color: darkgray;
                border-left-style: solid;
            }
            QComboBox::down-arrow {
                image: url(down_arrow.png);
            }
            QComboBox:hover {
                background-color: rgba(255, 182, 193, 128);
            }
        """)
        mode_combobox.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)
        mode_combobox.currentIndexChanged.connect(update_mode)

        global style_combobox
        style_combobox = QComboBox()
        style_combobox.addItems(["Cross", "Aword"])
        style_combobox.setCurrentText(crosshair_style)
        style_combobox.setStyleSheet("""
            QComboBox {
                background-color: rgba(255, 192, 203, 128);
                border-radius: 15px;
                padding: 5px;
                width: 100px;
                height: 30px;
            }
            QComboBox::drop-down {
                subcontrol-origin: padding;
                subcontrol-position: top right;
                width: 20px;
                border-left-width: 1px;
                border-left-color: darkgray;
                border-left-style: solid;
            }
            QComboBox::down-arrow {
                image: url(down_arrow.png);
            }
            QComboBox:hover {
                background-color: rgba(255, 182, 193, 128);
            }
        """)
        style_combobox.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)
        style_combobox.currentIndexChanged.connect(self.update_style_with_mod_check)

        hint_label = QLabel(
            "作者：哔哩哔哩令狐冰璃 v3.4 \n-- 右键点击切换准星可见性，按下 F10 键退出 \n 按下开镜Short Press \n长按开镜Long Press")
        hint_label.setAlignment(Qt.AlignCenter)
        hint_label.setStyleSheet("""
            background-color: rgba(255, 192, 203, 128);
            border-radius: 15px;
            padding: 10px;
        """)

        button_layout = QHBoxLayout()
        button_layout.addStretch()
        button_layout.addWidget(update_button)
        button_layout.addWidget(mod_crosshair_button)
        button_layout.addStretch()

        combobox_layout = QHBoxLayout()
        combobox_layout.addStretch()
        combobox_layout.addWidget(mode_combobox)
        combobox_layout.addStretch()

        style_combobox_layout = QHBoxLayout()
        style_combobox_layout.addStretch()
        style_combobox_layout.addWidget(style_combobox)
        style_combobox_layout.addStretch()

        main_layout.addLayout(button_layout)
        main_layout.addLayout(combobox_layout)
        main_layout.addLayout(style_combobox_layout)
        main_layout.addWidget(hint_label)

        container = QWidget()
        container.setLayout(main_layout)
        self.setCentralWidget(container)

        self.overlay = Overlay()
        self.overlay.show()

        self.mouse_listener = mouse.Listener(on_click=on_click)
        self.mouse_listener.start()

        self.timer = QTimer()
        self.timer.timeout.connect(self.update_crosshair_state)
        self.timer.start(1)

        redraw_crosshair(self)  # 初始绘制准星

    def load_mod_crosshair(self):
        global mod_crosshair_path
        if mod_crosshair_path and os.path.exists(mod_crosshair_path):
            self.current_mod_image = cv2.imread(mod_crosshair_path, cv2.IMREAD_UNCHANGED)
            if self.current_mod_image is None:
                print(f"Failed to load mod crosshair image: {mod_crosshair_path}")
                self.current_mod_image = None
        else:
            self.current_mod_image = None

    def select_mod_crosshair(self):
        global mod_crosshair_path
        mod_crosshair_path, ok = QFileDialog.getOpenFileName(None, "选择自定义准星图像", "", "Images (*.png *.jpg *.jpeg)")
        if ok:
            self.load_mod_crosshair()
            write_config()
            redraw_crosshair(self)

    def update_style_with_mod_check(self, index):
        global crosshair_style
        crosshair_style = style_combobox.itemText(index)
        if crosshair_style in ["Cross", "Aword"]:
            self.current_mod_image = None  # 重置自定义准星图像
        write_config()
        redraw_crosshair(self)

    def update_crosshair_state(self):
        try:
            self.overlay.update()

            if keyboard.is_pressed('f10'):
                self.close()

        except KeyboardInterrupt:
            print("程序被手动中断")
            self.close()

    def closeEvent(self, event):
        self.overlay.close()
        event.accept()

if __name__ == "__main__":
    app = QApplication(sys.argv)
    app.setWindowIcon(QIcon('data/sk.ico'))
    window = MainWindow()
    window.show()
    sys.exit(app.exec_())